import { Popover } from "@radix-ui/themes";
import { ToggleButton, ToggleGroupButton, ToggleGroupContainer } from "../components/ToggleButton";
import { RichEditorProps } from "../toolbar";
import { useCallback, useMemo } from "react";
import onClickify from "../libs/onClickify";
import { RichUtils } from "draft-js";


const h = ["one", "two", "three", "four", "five", "six"]
const blockTypes = new Array(3).fill(0).map((_, key) => ({
    label: `H${key + 1}`,
    style: `header-${h[key]}`,
}))
const HEADER = ({ editorState, onChange }: RichEditorProps) => {
    const blockStyle = useMemo(() => {
        const selection = editorState.getSelection();
        try {
            return editorState.getCurrentContent().getBlockForKey(
                selection.getStartKey()
            ).getType();
        } catch (e) {
            console.log("error", e);
            return "";
        }
    }, [editorState]);
    const Hn = useMemo(() => blockTypes.find(e => e.style === blockStyle)?.style, [blockStyle]);
    return (
        <ToggleGroupContainer>
            {blockTypes.map(({ label, style }) => (
                <ToggleGroupButton
                    key={label}
                    onMouseDown={onClickify(() => {
                        onChange(
                            RichUtils.toggleBlockType(editorState, style)
                        )
                    })}
                    value={style}
                    checked={Hn === style}
                >
                    {label}
                </ToggleGroupButton>
            ))}
        </ToggleGroupContainer>
    )
}
export default HEADER